﻿Imports System.IO
Imports System.Xml

Public Class frmFerramentasBuscarXML
    'Private arrAutorizacoes As New ArrayList
    Private strCurrentTagFind As String = ""
    Private blnSensitive As Boolean, blnStopSearch As Boolean

    Private Sub frmFerramentasBuscarProtocolos_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Call SalvaConfig("repro.busca.default.dir", txtPastaProtocolos.Text)
    End Sub

    Private Sub frmFerramentasBuscarProtocolos_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Enabled = False
        Call MontaGrid()
        Call PopularCombo()
        txtPastaProtocolos.Text = BuscaConfig("repro.busca.default.dir")
        Me.Enabled = True
    End Sub

    Private Sub MontaGrid()
        Try
            With dgvXMLs
                .SelectionMode = DataGridViewSelectionMode.CellSelect
                .AllowUserToAddRows = False
                .AllowUserToDeleteRows = False
                .AllowUserToResizeRows = False
                '.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray'-- zebrado
                .ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                .MultiSelect = False
                '.ConnectionString = strMyDBString
                '.SQL = ""
                .AddColumn("SEL", 35, True, DataGridViewContentAlignment.MiddleCenter)
                .AddColumn("Caminho", 0)
                .AddColumn("Valor", 0)
                .AddColumn("XML", 40, , DataGridViewContentAlignment.MiddleCenter)
                .AddColumn("Mensagem", 0)
                .FillColumns()
                .SelCell("SEL")
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub PopularCombo()
        Try
            With cmbTipoXML
                .Add("Protocolos de Autorização de Uso (*procNFe.xml)", "*procNFe.xml", "/nfeProc")
                .Add("Protocolos de Cancelamento de Uso (*procCancNFe.xml)", "*procCancNFe.xml", "/procCancNFe")
                .Add("NFe (*-nfe*.xml)", "*-nfe*.xml", "/NFe")
                .Add("Envio de Lote (*-env-lot*.xml)", "*-env-lot*.xml", "/enviNFe")
                '.Add("Recibos de Lote (*-rec*.xml)", "*-rec*.xml")
                '.Add("Consulta de Situação do Recibo (*-ped-rec*.xml)", "*-ped-rec*.xml")
                '.Add("Resposta da Situação do Recibo (*-pro-rec*.xml)", "*-pro-rec*.xml")
                '.Add("Consulta de Status do Serviço (*-ped-sta*.xml)", "*-ped-sta*.xml")
                '.Add("Resposta do Status do Serviço (*-sta*.xml)", "*-sta*.xml")
                .Add("Arquivos XML (*.xml)", "*.xml", "")
                .SelectedIndex = 0
            End With
            With cmbSearchCase
                .Add("Que contenha", "*value*")
                .Add("Exatamente", "value")
                .SelectedIndex = 0
            End With
            With cmbAcao
                .Add("Selecionar todos", "select.all")
                .Add("Deselecionar todos", "unselect.all")
                .Add("Copiar para a pasta...", "copy.to")
                .SelectedIndex = 0
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub cmdBuscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBuscar.Click
        Dim intFiles As Int16
        If IsEmpty(txtPastaProtocolos.Text) Then
            Call MsgBox("Caminho inválido!", MsgBoxStyle.Exclamation)
            txtPastaProtocolos.Select()
            Exit Sub
        End If
        If IsEmpty(txtValor.Text) Then
            Call MsgBox("Campo deve ser preenchido!", MsgBoxStyle.Exclamation)
            txtValor.Select()
            Exit Sub
        End If
        Call CurrentTegFind()
        cmdCancelar.Select()
        intFiles = VarrePasta()
        lblStatus.Text = dgvXMLs.RowCount & "/" & intFiles & " Arquivo(s) Encontrado(s) "
    End Sub

    Private Sub CurrentTegFind()
        Dim arrTags() As String
        Dim strXPath As String
        If cmbTemplateItens.Value <> "#" Then
            strXPath = cmbTemplateItens.Value
        Else
            strXPath = txtXPath.Text
        End If
        arrTags = Split(strXPath, "/")
        strCurrentTagFind = arrTags(arrTags.Length - 1)
    End Sub

    Private Function VarrePasta() As Int16
        Dim intCount As Int16
        Try
            Dim Path As String = txtPastaProtocolos.Text
            Dim Files As String, FilePattern As String = ""
            Dim Folders As String
            Dim strXPath As String = cmbTipoXML.ValueHidden & IIf(cmbTemplateItens.Value <> "#", cmbTemplateItens.Value, txtXPath.Text)
            Dim strValue As String = cmbSearchCase.Value.ToString.Replace("value", txtValor.Text)

            dgvXMLs.Rows.Clear()

            FilePattern = cmbTipoXML.Value
            '-- Verifico as autorizações nos diretorio raiz do caminho
            For Each Files In Directory.GetFiles(Path, FilePattern)
                Application.DoEvents()
                lblStatus.Text = Files
                intCount += 1
                Call VerificaXML(Files, strXPath, strValue)
                If blnStopSearch = True Then Exit Try
            Next
            '-- Verifico as autorizações nos Subdiretorios
            For Each Folders In Directory.GetDirectories(Path)
                For Each Files In Directory.GetFiles(Folders, FilePattern)
                    Application.DoEvents()
                    lblStatus.Text = Files
                    intCount += 1
                    Call VerificaXML(Files, strXPath, strValue)
                    If blnStopSearch = True Then Exit Try
                Next
            Next
            Return intCount
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        Finally
            VarrePasta = intCount
            blnStopSearch = False
        End Try
    End Function

    Private Sub VerificaXML(ByVal strFilePath As String, _
                            ByVal strXPath As String, _
                            ByVal strValue As String)
        Try
            Dim myXMLFound As String = File.ReadAllText(strFilePath)
            Dim myXML As New XmlDocument()
            Dim intCount As Int16
            Dim strTempValor As String = ""
            Dim strNF As String = ""
            Dim blnWriteLine As Boolean

            myXMLFound = Replace(myXMLFound, " xmlns=""http://www.portalfiscal.inf.br/nfe""", "")

            With myXML
                .LoadXml(myXMLFound)

                For intCount = 0 To .SelectNodes(strXPath).Count - 1
                    blnWriteLine = False
                    strTempValor = .SelectNodes(strXPath).Item(intCount).InnerText
                    If blnSensitive = False Then
                        If strTempValor.ToLower Like strValue.ToLower Then
                            blnWriteLine = True
                        End If
                    Else
                        If strTempValor Like strValue Then
                            blnWriteLine = True
                        End If
                    End If
                    If blnWriteLine = True Then
                        With dgvXMLs
                            .Rows.Add()
                            '.TextMatrix(.RowCount - 1, 0) = strFilePath
                            .TextMatrix(.RowCount - 1, 1) = strFilePath
                            .TextMatrix(.RowCount - 1, 2) = strTempValor
                            .TextMatrix(.RowCount - 1, 3) = "OK"
                        End With
                    End If
                Next
            End With
        Catch ex As Exception
            With dgvXMLs
                .Rows.Add()
                '.TextMatrix(.RowCount - 1, 0) = strFilePath
                .TextMatrix(.RowCount - 1, 1) = strFilePath
                .TextMatrix(.RowCount - 1, 2) = ""
                .TextMatrix(.RowCount - 1, 3) = "ERRO"
                .TextMatrix(.RowCount - 1, 4) = ex.Message
                .LineColor(.RowCount - 1, Color.Salmon)
            End With
        End Try
    End Sub

    Private Sub cmdPastaProtocolos_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPastaProtocolos.Click
        Call SetFolder(txtPastaProtocolos, "Pasta onde serão aramazenados os procolos de distribuição gerados automaticamente pelo aplicativo.")
    End Sub

    Private Sub SetFolder(ByVal objName As RePro.AnguloTextBox, ByVal strTexto As String)
        Dim myFolder As FolderBrowserDialog = New FolderBrowserDialog()
        With myFolder
            .SelectedPath = objName.Text
            .Description = strTexto
            .ShowDialog()
            objName.Text = .SelectedPath
        End With
    End Sub

    Private Function GetFolder(ByVal strTexto As String) As String
        Dim myFolder As FolderBrowserDialog = New FolderBrowserDialog()
        With myFolder
            .Description = strTexto
            .ShowDialog()
            Return .SelectedPath
        End With
    End Function

    Private Sub cmbTemplate_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbTemplate.SelectedIndexChanged
        Try
            With cmbTemplateItens
                .SQL = "SELECT id ||' - '|| path, path " & _
                       "FROM templates_itens " & _
                       "WHERE (elem='E' OR elem='CE') " & _
                       "AND id_template=" & cmbTemplate.Value & " " & _
                       "ORDER BY id ASC"
                .Reload()
                .Add("# PERSONALIZADO", "#")
                .SelectedIndex = -1
            End With
        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub cmbTipoXML_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbTipoXML.SelectedIndexChanged
        Try
            Dim strTemplate As String
            Select Case cmbTipoXML.ValueHidden
                Case "/nfeProc", "/NFe", "/enviNFe"
                    strTemplate = "NFeDados"
                Case "/procCancNFe"
                    strTemplate = "NFeCancela"
                Case Else
                    strTemplate = ""
            End Select
            With cmbTemplate
                .SQL = "SELECT template, id_template " & _
                       "FROM templates " & _
                       "WHERE template='" & strTemplate & "' " & _
                       "ORDER BY id_template ASC"
                .Reload()
            End With
            With cmbTemplateItens
                .Clear()
                .Add("# PERSONALIZADO", "#")
                .SelectedIndex = -1
            End With

        Catch ex As Exception
            Call SendError(ex.Message, ex.StackTrace)
        End Try
    End Sub

    Private Sub dgvXMLs_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvXMLs.CellDoubleClick
        With dgvXMLs
            If IsEmpty(.TextMatrix(e.RowIndex, 1)) Then Exit Sub
            If .TextMatrix(e.RowIndex, 3) = "ERRO" Then Exit Sub '-- Erro no XML
        End With

        Dim strFindTag As String = "<" & strCurrentTagFind & ">"
        Select Case e.ColumnIndex
            Case 1, 2
                With frmXMLViewer
                    .FilePath = dgvXMLs.TextMatrix(e.RowIndex, 1)
                    .FindString = strFindTag & dgvXMLs.TextMatrix(e.RowIndex, 2) & strFindTag.Replace("<", "</")
                    .FileReadOnly = True
                    .Open()
                End With
        End Select
    End Sub

    Private Sub cmbAcao_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbAcao.SelectedIndexChanged
        Dim intCount As Int16
        With dgvXMLs
            Select Case cmbAcao.Value
                Case "select.all"
                    For intCount = 0 To .Rows.Count - 1
                        .Rows(intCount).Cells("SEL").Value = "X"
                    Next
                Case "unselect.all"
                    For intCount = 0 To .Rows.Count - 1
                        .Rows(intCount).Cells("SEL").Value = ""
                    Next
                Case "copy.to"
                    Call CopiarPara()
            End Select
        End With
        cmbAcao.SelectedIndex = -1
    End Sub

    Private Sub CopiarPara()
        Dim strCopyPath As String = GetFolder("Selecione a pasta que deseja salvar uma cópia.")
        Dim intCount As Int32
        Dim strSourceFile As String = "", strDestFilename As String = ""
        Dim arrFile As Array

        If IsEmpty(strCopyPath) Then Exit Sub

        With dgvXMLs
            For intCount = 0 To .Rows.Count - 1
                If .Rows(intCount).Cells("SEL").Value = "X" Then
                    Application.DoEvents()
                    strSourceFile = .TextMatrix(intCount, 1)
                    arrFile = strSourceFile.Split("\")
                    strDestFilename = strCopyPath & "\" & arrFile.GetValue(arrFile.Length - 1)
                    Call File.Copy(strSourceFile, strDestFilename, True)
                    lblStatus.Text = strDestFilename
                End If
            Next
        End With
        lblStatus.Text = "Arquivos copiados com sucesso!"
    End Sub

    Private Sub cmbTemplateItens_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbTemplateItens.Leave
        If cmbTemplateItens.Value <> "#" Then
            txtXPath.Text = cmbTipoXML.ValueHidden & cmbTemplateItens.Value
        End If
    End Sub

    Private Sub chkSensitive_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkSensitive.CheckedChanged
        blnSensitive = chkSensitive.Checked
    End Sub

    Private Sub cmdCancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancelar.Click
        blnStopSearch = True
    End Sub
End Class